<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script type="text/javascript">

    var socket;

    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8899/ws");

        // 客户端收到服务器端的消息时回调
        socket.onmessage = function (event) {
            var mes = document.getElementById("responseText");
            mes.value = mes.value + "\n" + event.data;
        }

        // 连接建立成功时回调
        socket.onopen = function (event) {
            var mes = document.getElementById("responseText");
            mes.value = "连接开启！";
        }

        // 连接断掉时回调
        socket.onclose = function (event) {
            var mes = document.getElementById("responseText");
            mes.value = mes.value + "\n" + "连接关闭！";
        }
    } else {
        alert("浏览器不支持WebSocket！")
    }

    function send(message) {
        // 浏览器不支持，直接返回
        if (!window.WebSocket) {
            return;
        }

        // WebSocket已经打开
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("连接尚未开启");
        }
    }
</script>

<form onsubmit="return false;">
    <p>和第五个实例一起使用，测试WebSocket</p>
    <p>刷新页面会断开连接，然后重新建立连接</p>
    <textarea id="message" style="width:500px; height:300px"></textarea>
    <input type="button" value="发送数据" onclick="send(this.form.message.value)"/>

    <h3>服务端输出：</h3>

    <textarea id="responseText" style="width:500px; height:300px"></textarea>
    <input type="button" onclick="javascript: document.getElementById('responseText').value=''" value="清空内容"/>
</form>

</body>
</html>